package org.stwy.pro.asset;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.stwy.comm.base.BaseRecordsServiceImpl;
import org.stwy.pro.property.PropertyEntity;
import org.stwy.pro.property.PropertyService;

import com.google.gson.JsonArray;
import com.rap.common.exception.ServiceException;
import com.rap.common.persistence.IBaseDAO;
import com.rap.frame.attachment.AttachmentService;
import com.rap.frame.enumdata.EnumDataUtils;

/**
 * 物业 服务类
 */
/**
*版权信息 (c) RAP 保留所有权利.
*@author Rap.Codegen
*@Team RAP Team
*@Date 2015-4-4 17:05:42
*<p></p>
*
*@参与人：Rap.Codegen
*/
 
@Service
@Transactional(rollbackFor=Exception.class)
public class AssetService extends BaseRecordsServiceImpl<AssetEntity, String> {

	@Autowired
	private AssetDAO dao;
	
	@Autowired
	private AttachmentService attachmentService;
	
	@Autowired
	private PropertyService propertyService;
	
	@Override
	protected IBaseDAO getDAO() {
		return dao;
	}

	@Override
	protected Long getLastCode() throws ServiceException {
		Long lastCode = dao.getLastCode();
		if(lastCode==null){
			lastCode=0L;
		}
		return lastCode;
	}

	@Override
	protected String[] getRecordAttrs() throws ServiceException {
		return new String[]{"theName","property","assetState","area","region","usefor","groupOne","groupTwo"};
	}
	/**
	 * 根据code获取最后一条记录
	 * @param code
	 * @return
	 * @throws ServiceException
	 */
	public AssetEntity getLastRecordByCode(Long code) throws ServiceException {
		return dao.getLastByTheCode(code);
	}
	/**
	 * 根据code获取有效的记录
	 * @param code
	 * @return
	 * @throws ServiceException
	 */
	public AssetEntity getValidRecordByCode(Long code) throws ServiceException {
		return dao.getValidRecordByCode(code);
	}
	/**
	 * 添加资产变更记录
	 * @param record
	 * @param pks 
	 * @return
	 * @throws ServiceException
	 */
	public boolean addAssetRecord(RecordEntity record)  throws ServiceException{
		try{
			AssetEntity asset = get(record.getId());
			//检查变更时间是否合法
			checkRecordDate(asset.getTheCode(),record.getRecordDate());
			//检查状态变更是否合法
			checkChange(asset.getAssetState(),record.getStateAfter());
			AssetEntity newAsset = new AssetEntity();
			BeanUtils.copyProperties(asset, newAsset);
			
			//更新资产状态
			newAsset.setAssetState(record.getStateAfter());
			newAsset.setRecordDate(record.getRecordDate());
			newAsset.setCanNotRentType(record.getCanNotRentType());
			newAsset.setReason(record.getReason());
			update(newAsset);
		}catch(ServiceException e){
			 throw e;
		}catch(Exception e){
			e.printStackTrace();
			throw new ServiceException("系统异常，未完成变更");
		}
		return true;
	}
	/**
	 * 检查变更时间是否不小于上次变更时间
	 * @param theCode
	 * @param recordDate
	 * @throws ServiceException
	 */
	private void checkRecordDate(Long theCode, Date recordDate)  throws ServiceException {
		AssetEntity lastChange = getLastChangeByTheCode(theCode);
		if(lastChange!=null&&lastChange.getRecordDate()!=null){
			if(recordDate.before(lastChange.getRecordDate())){
				throw new  ServiceException("变更失败，变更时间小于上次变更时间");
			}
		}
	}

	public AssetEntity getLastChangeByTheCode(Long theCode) throws ServiceException  {
		List<AssetEntity> list =dao.getLastChangeByTheCode(theCode);
		if(list==null||list.size()==0){
			return null;
		}
		return list.get(0);
	}
	/**
	 * 批量添加变更记录
	 * @param record
	 * @param pks
	 * @return
	 * @throws ServiceException
	 */
	public boolean addAssetRecord(RecordEntity record, String[] pks)  throws ServiceException{
		for(String pk : pks){
			record.setId(pk);
			addAssetRecord(record);
		}
		return true;
	}
	/**
	 * 检查是否可以变更
	 * @param stateBefore
	 * @param stateAfter
	 */
	private void checkChange(String stateBefore, String stateAfter)  throws ServiceException{
		if(stateBefore==null||stateAfter==null){
			throw new ServiceException("记录状态为空，不能变更");
		}
		if(stateBefore.equals(stateAfter)){
			throw new ServiceException("变更前后状态相同，不能变更");
		}
		if(AssetEntity.ASSET_STATUS_NULL.equals(stateAfter)){
			
		}else if(AssetEntity.ASSET_STATUS_SELF.equals(stateAfter)){
			if(!stateBefore.equals(AssetEntity.ASSET_STATUS_NULL)){
				throw new ServiceException("资产不是空置状态，不能自用");
			}
		}else if(AssetEntity.ASSET_STATUS_RENT.equals(stateAfter)){
			if(!stateBefore.equals(AssetEntity.ASSET_STATUS_NULL)){
				throw new ServiceException("资产不是空置状态，不能出租");
			}
		}else if(AssetEntity.ASSET_STATUS_CANNOTRENT.equals(stateAfter)){
			if(!stateBefore.equals(AssetEntity.ASSET_STATUS_NULL)){
				throw new ServiceException("资产不是空置状态，不能撤销");
			}
		} 
	}

	/**
	 * 更新资产状态
	 * @param code
	 * @param newState
	 * @return
	 * @throws ServiceException
	 */
	private boolean changeAssetState(Long code,String assetState) throws ServiceException {
		AssetEntity asset = this.getLastRecordByCode(code);
		asset.setAssetState(assetState);
		this.update(asset);
		return true;
	}
	@Override
	protected void doBeforeSaveCopy(AssetEntity newEntity) {
		newEntity.setUuid(null);
		newEntity.setStatus(1);
		newEntity.setTheName("copy_"+newEntity.getTheName());
		newEntity.setAssetState(AssetEntity.ASSET_STATUS_NULL);
	}

	public void updateAssetFileState(String entityType, String entityUuid) throws ServiceException {
		List list = attachmentService.findByEntityUuidAndEntityType(entityUuid, entityType);
		AssetEntity entity = this.get(entityUuid);
		if(list!=null&&list.size()>0){
			entity.setFileCount(list.size());
		}else{
			entity.setFileCount(0);
		}
		this.save(entity);
	}
	
	public void importData(List<List<Object>> dataList) throws ServiceException{
		List<AssetEntity> saveList = new ArrayList<AssetEntity>();
		List errorList = new ArrayList();
		for(List<Object> rowData: dataList){
			
			String propertyName = (String)rowData.get(0);
			String assetName = (String)rowData.get(1);
			String assetStatus = (String)rowData.get(2);
			String area = ((String)rowData.get(3)).replaceAll(",","");
			String region = (String)rowData.get(4);
			String usefor = (String)rowData.get(5);
			String groupOne = (String)rowData.get(6);
			String groupTwo = (String)rowData.get(7);
			String address = (String)rowData.get(8);
			String houseCert = (String)rowData.get(9);
			String bookType = (String)rowData.get(10);
			String reason = (String)rowData.get(14);
			
			PropertyEntity propertyEntity = propertyService.getByPropertyName(propertyName);
			if(propertyEntity == null){
				errorList.add(rowData);
				continue;
			}
			
			AssetEntity asset = new AssetEntity();  
			asset.setProperty(propertyEntity);
			asset.setTheName(assetName);
			asset.setAddress(address);
			asset.setArea(Double.parseDouble(area));
			asset.setAssetState(EnumDataUtils.getEnumValueByName(assetStatus, "stwy_assetStatus"));
			asset.setBookType(EnumDataUtils.getEnumValueByName(bookType, "stwy_bookType"));
			asset.setCanNotRentType("3");//其他
			asset.setGroupOne(EnumDataUtils.getEnumValueByName(groupOne, "stwy_groupOne"));
			asset.setGroupTwo(EnumDataUtils.getEnumValueByName(groupTwo, "stwy_groupTwo"));
			asset.setHouseCert(houseCert);
			asset.setUsefor(EnumDataUtils.getEnumValueByName(usefor, "stwy_userfor"));
			asset.setRegion(EnumDataUtils.getEnumValueByName(region, "stwy_region"));
			asset.setReason(reason);
			saveList.add(asset);
		}
		System.out.println(JSONArray.fromObject(errorList).toString());
		save(saveList);
	}
}
